﻿#include "FormMain.h"
#include "ui_FormMain.h"
#include "FormConfig.h"
#include "FormHpConfig.h"
#include "FormCalib.h"
#include <QTimer>
#include <QFileDialog>


FormMain::FormMain(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FormMain)
{
    ui->setupUi(this);

    setWindowIcon(QIcon(":/Other/Image/HP.png"));
    setWindowTitle("HP辅助软件V1.0");

    RangList<<"0.1N"<<"0.2N"<<"0.3N"<<"0.5N"
    <<"1N"<<"2N"<<"3N"<<"5N"<<"10N"<<"20N"<<"30N"<<"50N"<<"100N"<<"200N"<<"300N"<<"500N"
    <<"1KN"<<"2KN"<<"3KN"<<"5KN"<<"10KN"<<"20KN"<<"30KN"<<"50KN"<<"100KN"
    <<"200KN"<<"300KN"<<"500KN"<<"1000KN"<<"2000KN"<<"3000KN"<<"5000KN";

    UnitList<<"N"<<"KN"<<"GF"<<"KGF"<<"TF"<<"LBF"<<"KLBF";

    connect(FormConfig::getInstance()->p_HP,SIGNAL(&AcqPressure::SigAcqpre),this,SLOT( RecvAcqpre));

    InitChart();
    //连接配置
    connect(ui->Btn_Connect,&QPushButton::clicked,[=](){
        FormConfig::getInstance()->show();
        FormConfig::getInstance()->activateWindow();
    });
    //参数配置
    connect(ui->Btn_Config,&QPushButton::clicked,[=](){
        FormHpConfig::getInstance()->show();
        FormHpConfig::getInstance()->activateWindow();
    });
    //标定
    connect(ui->Btn_Calibn,&QPushButton::clicked,[=](){
        FormCalib::getInstance()->show();
        FormCalib::getInstance()->activateWindow();
    });


    //开始采集
    connect(ui->Chk_Start,&QCheckBox::clicked,[=](){
        if(!FormConfig::getInstance()->p_HP->isConnect)
        {
            QMessageBox::information(this,"提示","检查是否已经连接!");
            ui->Chk_Start->setChecked(false);
            return;
        }
        FormConfig::getInstance()->p_HP->isStart=ui->Chk_Start->isChecked();
    });
    //设置频率
    connect(ui->Sb_Fre,QOverload<int>::of(&QSpinBox::valueChanged),[=](int fre){
        FormConfig::getInstance()->p_HP->Fre=fre;
    });
    //清理界面
    connect(ui->Btn_Clear,&QPushButton::clicked,[=](){
        ClearChart();
        });
    //开始记录
    connect(ui->Chk_Record,&QCheckBox::clicked,[=](){
        if(RecordFileName==""||!FormConfig::getInstance()->p_HP->isConnect)
        {
            QMessageBox::information(this,"提示","检查是否设置记录目录!\n检查是否已经连接!");
            ui->Chk_Record->setChecked(false);
            return;
        }
        if(ui->Chk_Record->isChecked())
        {
            AutoRcNameSimple();
        }
    });
    //分析窗口
    connect(ui->Btn_Fx,&QCheckBox::clicked,[=](){
        FxForm::getInstance()->show();
    });

    //导入数据
    connect(ui->Btn_Export,&QPushButton::clicked,[=](){
        //停止记录
        if(ui->Chk_Record->isChecked())
        {
            ui->Chk_Record->setChecked(false);
        }
        //停止采集
        if(ui->Chk_Start->isChecked())
        {
            ui->Chk_Start->setChecked(false);
        }
        //清空数据
        ClearChart();

        QStringList listFile = QFileDialog::getOpenFileNames(this, "请选择保存项目文件路径", RecordFileName, "*.csv");
        if(listFile.count()==0)
            return;
        FxForm::getInstance()->GetFpsData(listFile,RCList);

        for (int var = 0; var < RCList.count(); ++var) {
            //添加到曲线控件
            ui->widget_Chart->graph(0)->addData((double)var,FormConfig::getInstance()->p_HP->s_HpData.Up);
            ui->widget_Chart->graph(1)->addData((double)var,RCList.at(var).data);
            ui->widget_Chart->graph(2)->addData((double)var,FormConfig::getInstance()->p_HP->s_HpData.Down);
            pCustomPlot->SetLabelText(0,FormConfig::getInstance()->p_HP->s_HpData.Up);
            pCustomPlot->SetLabelText(1,RCList.at(var).data);
            pCustomPlot->SetLabelText(2,FormConfig::getInstance()->p_HP->s_HpData.Down);
        }
        ui->widget_Chart->xAxis->rescale(true);
        ui->widget_Chart->yAxis->rescale(true);
        ui->widget_Chart->replot(QCustomPlot::rpQueuedReplot);
    });
    //初始化记录目录
    QSettings mSettings(QDir::currentPath()+"/Settings.ini",QSettings::IniFormat);
    mSettings.setIniCodec(QTextCodec::codecForName("UTF-8"));
    RecordFileName=mSettings.value("Record/Path").toString();
    ui->Lb_Path->setText(RecordFileName);

    QDir dir(RecordFileName);
    if(!dir.exists())
    {
        dir.mkpath(RecordFileName);
    }
    connect(ui->Btn_Path,&QPushButton::clicked,[=](){
        RecordFileName = QFileDialog::getExistingDirectory(this,tr("请选择记录数据目录"),RecordFileName);
        if(!RecordFileName.isEmpty())
        {
            QSettings mSettings(QDir::currentPath()+"/Settings.ini",QSettings::IniFormat);
            mSettings.setIniCodec(QTextCodec::codecForName("UTF-8"));
            mSettings.setValue("Record/Path",RecordFileName);
            ui->Lb_Path->setText(RecordFileName);
        }
    });

    //保存图片
    connect(ui->Btn_SaveImg,&QPushButton::clicked,[=](){
        QString fileName = QFileDialog::getSaveFileName(this,"保存当前图像",
                                                            RecordFileName,
                                                            "(*.png)");

        ui->widget_Chart->savePng(fileName);

    });
    QTimer *RunTimer=new QTimer();
    connect(RunTimer,SIGNAL(timeout()),this,SLOT(TimeUpdate()));
    RunTimer->start(100);
}

FormMain::~FormMain()
{
    delete ui;
}
void FormMain::closeEvent(QCloseEvent *event)
{
    if(FormConfig::getInstance()->isVisible())
        FormConfig::getInstance()->close();
    if(FormHpConfig::getInstance()->isVisible())
        FormHpConfig::getInstance()->close();
}

void FormMain::InitChart()
{
    pCustomPlot=new OpratChart(this,ui->widget_Chart);
    pCustomPlot->AddGraphs("F_Hig",QColor("#FB0000"));
    pCustomPlot->AddGraphs("F_Act",QColor("#00FB00"));
    pCustomPlot->AddGraphs("F_Low",QColor("#0000FB"));
    //pCustomPlot->SetTrance(ui->widget_Chart->graph(1));
    //pCustomPlot->SetShowTracer(false);
}
void FormMain::AutoRcNameSimple()
{
    RcFileCount++;
    RcFileName=RecordFileName+"/"+QDateTime::currentDateTime().toString("yyyyMMdd_HHmmss")+"_No"+QString::number(RcFileCount)+".csv";
    RcfileSave.setFileName(RcFileName);
    if(RcfileSave.open(QIODevice::WriteOnly))
    {
        RcStream.setDevice(&RcfileSave);
        RcStream.setCodec("utf-8");
    }
}
void FormMain::ClearChart()
{
    PtCount=0;
    ui->widget_Chart->graph(0)->data()->clear();
    ui->widget_Chart->graph(0)->addData(0,0);
    pCustomPlot->SetLabelText(0,0);
    ui->widget_Chart->graph(1)->data()->clear();
    ui->widget_Chart->graph(1)->addData(0,0);
    pCustomPlot->SetLabelText(1,0);
    ui->widget_Chart->graph(2)->data()->clear();
    ui->widget_Chart->graph(2)->addData(0,0);
    pCustomPlot->SetLabelText(2,0);
    ui->widget_Chart->replot();
}


void FormMain::RecvAcqpre()
{
    //曲线添加数据
    ui->widget_Chart->graph(0)->addData((double)PtCount,FormConfig::getInstance()->p_HP->s_HpData.Up);
    ui->widget_Chart->graph(1)->addData((double)PtCount,FormConfig::getInstance()->p_HP->s_HpData.Value);
    ui->widget_Chart->graph(2)->addData((double)PtCount,FormConfig::getInstance()->p_HP->s_HpData.Down);
    pCustomPlot->SetLabelText(0,FormConfig::getInstance()->p_HP->s_HpData.Up);
    pCustomPlot->SetLabelText(1,FormConfig::getInstance()->p_HP->s_HpData.Value);
    pCustomPlot->SetLabelText(2,FormConfig::getInstance()->p_HP->s_HpData.Down);
    PtCount++;

    //记录数据
    static int fpsCount=0;
    if(ui->Chk_Record->isChecked())
    {
        if(RcfileSave.isOpen())
        {
            QString data=QString("%1,%2\n")
                    .arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss.zzz"))
                    .arg(FormConfig::getInstance()->p_HP->s_HpData.Value);
            RcStream<<data;
            fpsCount++;
        }
        if(fpsCount>=ui->spinBox_RcPacket->value())//根据分包大小记录文件
        {
            if(RcfileSave.isOpen())
                RcfileSave.close();
            fpsCount=0;
            AutoRcNameSimple();
        }
    }
    else
    {
        if(RcfileSave.isOpen())
            RcfileSave.close();
        fpsCount=0;
    }
    //曲线控件刷新
    ui->widget_Chart->graph(0)->data()->removeBefore(PtCount-ui->widget_Chart->xAxis->range().size());
    ui->widget_Chart->graph(1)->data()->removeBefore(PtCount-ui->widget_Chart->xAxis->range().size());
    ui->widget_Chart->graph(2)->data()->removeBefore(PtCount-ui->widget_Chart->xAxis->range().size());
    ui->widget_Chart->xAxis->setRange(PtCount-ui->widget_Chart->xAxis->range().size(), PtCount);
    ui->widget_Chart->yAxis->rescale(true);
    ui->widget_Chart->replot(QCustomPlot::rpQueuedReplot);
}
void FormMain::TimeUpdate()
{
    //连接状态
    static QIcon cntOn(":/Other/Image/Port2.png");
    static QIcon cntOff(":/Other/Image/Port1.png");
    if(FormConfig::getInstance()->p_HP->isConnect)
        ui->Btn_Connect->setIcon(cntOn);
    else
        ui->Btn_Connect->setIcon(cntOff);

    //显示量程
    if(FormConfig::getInstance()->p_HP->s_HpData.Range<=RangList.count())
        ui->Lb_Range->setText(RangList.at(FormConfig::getInstance()->p_HP->s_HpData.Range));
    //当前值
    if(FormConfig::getInstance()->p_HP->s_HpData.unit<=UnitList.count())
        ui->Lb_Act->setText(QString("%1 %2")
                            .arg(FormConfig::getInstance()->p_HP->s_HpData.Value)
                            .arg(UnitList.at(FormConfig::getInstance()->p_HP->s_HpData.unit)));
}

